<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建
      </el-button>      
    </div>
    <div class=" h-5"></div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
    <!--
      <el-table-column
        :label="t('message.layout.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template #default="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      -->
      <el-table-column
        :prop="monitorName"
        label="监控名称"
        width="140"
        align="center"
      >
        <template #default="{row}">
          <el-tag>{{ row.monitorName }}</el-tag>
        </template>
      </el-table-column>

	  <el-table-column
        label="地址"
        align="center"
      >
        <template #default="{row}">
          <span>{{row.monitorAddr}} </span>
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template #default="{row, $index}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            {{ t("message.layout.edit") }}
          </el-button>  
          <!--
          <el-button            
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            {{ t("message.layout.draft") }}
          </el-button>
          -->
          <el-popconfirm title="是否确定删除?" @confirm="handleDelete(row, $index)">
            <template #reference>
               <el-button
                size="mini"
                type="danger"
              >
                {{ t("message.layout.delete") }}
          </el-button>
            </template>
          </el-popconfirm>
         
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="total"
      v-if="false"
      v-model:page="listQuery.currentPage"
      v-model:limit="listQuery.pageCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempArticleModel"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="监控名称"  prop="monitorName">
          <el-input
            v-model="tempArticleModel.monitorName"
            placeholder="请输入监控名称"
          />
        </el-form-item>

         <el-form-item label="监控地址"  prop="monitorAddr">
          <el-input
            v-model="tempArticleModel.monitorAddr"
            placeholder="请输入监控地址"
          />
        </el-form-item>

        <div class=" h-4"></div>
        <el-form-item v-if="false" :label="t('message.layout.isPhone')" prop="importance">
          <el-select
            v-model="tempArticleModel.importance"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in importanceOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>         

        <el-form-item  v-if="false" :label="t('message.layout.isautoRec')"  prop="status">
          <el-select
            v-model="tempArticleModel.status"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item  v-if="false" :label="t('message.layout.mainRen')" prop="reviewer">
          <el-input
            v-model="tempArticleModel.reviewer"
            :autosize="{minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="主要责任人"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex ">
        <el-button @click="dialogFormVisible = false">
          {{ t("message.layout.cancel") }}
        </el-button>
        <div class=" w-10"></div>
        <el-button
          type="primary"
          @click="createData()"
        >
          {{ t("message.layout.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-model:visible="dialogPageviewsVisible"
      title="Reading statistics"
    >
      <el-table
        :data="pageviewsData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          prop="key"
          label="Channel"
        />
        <el-table-column
          prop="pageviews"
          label="Pageviews"
        />
      </el-table>
      <span class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogPageviewsVisible = false"
        >{{
          t("message.layout.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang='ts'>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  unref,
onUnmounted
} from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  deleteArticle,
  updateArticle,
  defaultArticleModel,
  ArticleType
} from '/@/request/articles'
import { ArticleModel } from '/@/model/articleModel'

//import { exportJson2Excel } from '@/utils/excel'
//import { formatJson } from '@/utils'
import { useI18n } from 'vue-i18n'
//import zhihuiJigouJson from '/@/mock/yujingShezhi.json';
// import Pagination from '@/components/Pagination/index.vue'
import '/@/assets/iconfont/iconfont.css'
import VoiceRecordUnit from '/@/utils/shf/VoiceRecordUnit'
import VoiceUnit from '/@/utils/shf/VoiceUnit'
import HttpReqApi from '/@/utils/shf/http/HttpReqApi'
import MittUnit, { MittEvent } from '/@/utils/shf/MittUnit'
import Assert from '/@/utils/shf/Assert'
import MonitorUnit from '/@/utils/shf/MonitorUnit'
import ReqEasyMedia from '/@/request/ReqEasyMedia'
export default defineComponent({
  components: {
    // Pagination
  },
  setup() {
     
     onMounted(async () => {
    
      console.log(typeof ElForm);
      // dataMap.getList(null, null, 10);
      // MittUnit.on(MittEvent.updateEquipSuccess,updateEquipSuccess);
      dataMap.listLoading = false;
      // let res:any = await HttpReqApi.getEquips();
      updateEquipSuccess();
    })
    onUnmounted(()=>{
      // MittUnit.off(MittEvent.updateEquipSuccess,updateEquipSuccess);
    })
    const updateEquipSuccess = async ()=>{
        dataMap.dialogFormVisible = false;
        let res:any = null;
        try {
          res = await ReqEasyMedia.use().getList();
        } catch (error) {
          return;
        }
        
        let copyDataArr:any[] = [];
        let dataArr:any[] = [];
        for (const montiordata of res) {
            let one:any = {monitorAddr:montiordata.url,monitorName:montiordata.remark,id:montiordata.mediaKey};
            dataArr.push(one);
            copyDataArr.push({...one});
        }
        dataMap.list=dataArr;

        MonitorUnit.saveSession(copyDataArr);
        
        //  console.log(ArticleModel)
        //     const addData=await HttpReqApi.updateEquip(ArticleModel).then(async() => {
		    //     ElMessage.success('添加成功')
		    //     dataMap.dialogFormVisible = false
		    //     const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)
		    //     //const data=zhihuiJigouJson        
		    //     dataMap.list = data?.data ?? []
		    //     dataMap.total = data?.total ?? 0
		    //   }).catch(err => {
		    //   ElMessage.warning('添加错误')
		    //  });
    };
    const { t } = useI18n()
    const tagArr = ['温度','湿度','氧气','一氧化碳','二氧化碳','压力','甲烷','渗漏水','入侵','消防烟感','消防温感','消防手报','机电','突发'];
    const calendarTypeOptions = ['无告警','短信模板A','短信模板B','短信模板C','短信模板D','短信模板E','短信模板F','短信模板G']
	const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string }
    const dataForm = ref(ElForm)
    const dataMap = reactive({
      tableKey: 0,
      list: Array<ArticleModel>(),
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageCount: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      listfilter:tagArr.map((item)=>{return {text:item,value:item}}),

	  monObjectOptions:tagArr,
    
      importanceOptions: ['无告警','文字语音模板A', '文字语音模板B', '文字语音模板C', '文字语音模板D', '文字语音模板E', '文字语音模板F', '文字语音模板G'],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      statusOptions: ['自动归档', '手动归档'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },

      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        monitorAddr: [
          { required: true, message: '监控地址未填写', trigger: 'change' }
        ],
        monitorName: [
          { required: true, message: '监控名未填写', trigger: 'change' }
        ],
      },
      downloadLoading: false,
      tempArticleModel: {
        id: '',
        monitorAddr: '',
        monitorName: ''
      },
      handleCurrentChange(page?: any) {
        dataMap.getList(page)
      },
      handleSizeChange(val: any) {
        dataMap.getList(null, null, val)
      },
      async getList(page?: any, total?: any, limit?: any,data?:any) {
        return;
        if (page) {
          dataMap.listQuery.currentPage = page
        }
        if (limit) {
          dataMap.listQuery.pageCount = limit
        }
        console.log(total)
        dataMap.listLoading = true

        if (data){
        	dataMap.list = data.data
        	dataMap.total = data.total
        }
        else{
        const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)
        //const data=zhihuiJigouJson        
        dataMap.list = data?.data ?? []
        dataMap.total = data?.total ?? 0
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          dataMap.listLoading = false
        }, 0.5 * 1000)
      },
      handleFilter() {
        dataMap.listQuery.currentPage = 1
        dataMap.getList()

        

      },
      listfilterFun(
        value: string,
        row: any
      ) {
        return row.equipName === value
      },
      handleModifyStatus(row: any, status: string) {
      /*
        ElMessage.success({
          message: '操作成功',
          type: 'success'
        })
        row.status = status*/
      },
      sortChange(data: any) {
        const { prop, order } = data
        if (prop === 'id') {
          dataMap.sortByID(order)
        }
      },
      sortByID(order: string) {
        if (order === 'ascending') {
          dataMap.listQuery.sort = '+id'
        } else {
          dataMap.listQuery.sort = '-id'
        }
        dataMap.handleFilter()
      },
      getSortClass(key: string) {
        const sort = dataMap.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      resetTempArticleModel() {
        dataMap.tempArticleModel = {
        id: '',
          monitorAddr: '',
          monitorName: ''
      };
      },
      handleCreate() {
        console.log('添加了')
        dataMap.resetTempArticleModel()
        dataMap.dialogStatus = 'create'
        dataMap.dialogFormVisible = true
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      createData() {
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const ArticleModel = dataMap.tempArticleModel;
            console.log('temAricleModel = ',dataMap.tempArticleModel);
            if(ArticleModel.id == ''){
              //新增
              await ReqEasyMedia.use().add(dataMap.tempArticleModel);
              ElMessage.success({
                message: '新增成功',
                type: 'success',
                duration: 2000
              });
              updateEquipSuccess();
              return;
            }
            
            await ReqEasyMedia.use().edit(dataMap.tempArticleModel);
            ElMessage.success({
              message: '修改成功',
              type: 'success',
              duration: 2000
            });
            updateEquipSuccess();
            return;
            //ArticleModel.id = Math.round(Math.random() * 100) + 1024 // mock a id
            //ArticleModel.author = 'RCYJ_Scy'
           
		     
			/*
            if (addData?data.id) {
              alert(addData.data.id)
              console.log(addData)
              dataMap.list.unshift(addData.data)
            }
			
            */
            
          }
        })
      },

      handleUpdate(row: any) {

        console.log('添加了',row);
        dataMap.resetTempArticleModel();
        dataMap.tempArticleModel.id = row.id;
        dataMap.tempArticleModel.monitorAddr = row.monitorAddr;
        dataMap.tempArticleModel.monitorName = row.monitorName;
        dataMap.dialogStatus = 'update';
        dataMap.dialogFormVisible = true;
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      updateData() {
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const tempData = Object.assign({}, dataMap.tempArticleModel)
            //tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            console.log(tempData)
            const data = await updateArticle(tempData,ArticleType.YJSZ).then(async()=>{
	        	ElMessage.success('更新成功')
		        dataMap.dialogFormVisible = false
		        const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)		                
		        dataMap.list = data?.data ?? []
		        dataMap.total = data?.total ?? 0	
            }).catch(err => {
		      ElMessage.warning('更新失败')
		    });
			/*
            console.log(data, '-----------------')
            if (data) {
              const index = dataMap.list.findIndex(
                (v) => v.id === data.data.id
              )
              dataMap.list.splice(index, 1, data.data)
            }

            dataMap.dialogFormVisible = false
            ElMessage.success({
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            */
          }
        })
      },
      async handleDelete(row: any, index: number) {
        await ReqEasyMedia.use().del(row);
         ElMessage.success({
          message: '删除成功',
          type: 'success',
          duration: 2000
        });
        dataMap.list.splice(index, 1);
      // 	await deleteArticle(row.id,ArticleType.YJSZ).then(()=>{
      //   ElMessage.success({
      //     message: '删除成功',
      //     type: 'success',
      //     duration: 2000
      //   })
      //   dataMap.list.splice(index, 1)
      //   }).catch(err => {
	    //   ElMessage.warning('删除失败')
	    //  });
      },
      async handleGetPageviews(pageviews: string) {
        const data = await getPageviews({ pageviews })
        //const data = zhihuiJigouJson.data;
        dataMap.pageviewsData = data?.data.pageviews
        console.log(dataMap.pageviewsData)
        dataMap.dialogPageviewsVisible = true
      },
      handleDownload() {
        dataMap.downloadLoading = true
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        //const data = formatJson(filterVal, dataMap.list)
        //exportJson2Excel(tHeader, data, 'table-list')
        dataMap.downloadLoading = false
      },
      typeFilter: (type: string) => {
        return calendarTypeKeyValue[type]
      },
     
   
      
    })
    
    return { t,...toRefs(dataMap), dataForm }
  }
})
</script>
